package com.eusoft.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.eusoft.demo.entity.Car;
import com.eusoft.demo.entity.CarState;
import com.eusoft.demo.entity.CarType;
import com.eusoft.demo.entity.CarUser;
import com.eusoft.demo.mapper.CarMapper;
import com.eusoft.demo.mapper.CarUserMapper;
import com.eusoft.demo.query.CarListQuery;
import com.eusoft.demo.query.QueryCheckCarPlateCode;
import com.eusoft.demo.service.ICarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eusoft.demo.service.ICarStateService;
import com.eusoft.demo.service.ICarTypeService;
import com.eusoft.demo.service.ICarUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 车辆 服务实现类
 * </p>
 *
 * @author DevMing
 * @since 2021-08-19
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {
    @Resource
    private CarUserMapper carUserMapper;

    @Autowired
    private ICarService carService;

    @Autowired
    private ICarTypeService carTypeService;

    @Autowired
    private ICarStateService carStateService;

    @Autowired
    private ICarUserService carUserService;


    /**
     * 获取车辆列表
     *
     * @param query
     * @return
     */
    @Override
    public HashMap<Object, Object> getCarList(CarListQuery query) {
        //对传回的参数进行判空处理
        if (query == null) {
            System.out.println("null");
            query = new CarListQuery();
            query.setId(-1);
            query.setSearch(null);
            query.setStateId(-1);
            query.setPage(1);
            query.setPageRows(10);
        } else {
            if (query.getId() == null) {
                System.out.println("typeID");
                query.setId(-1);
            }
            if (query.getStateId() == null) {
                query.setStateId(-1);
            }
            if (query.getPage() == null) {
                query.setPage(1);
            }
            if (query.getPageRows() == null) {
                query.setPageRows(10);
            }
        }
        Integer typeId = query.getId();
        System.out.println(typeId);
        Integer stateId = query.getStateId();
        String plate_code = query.getSearch();
        Integer page = query.getPage();
        Integer pageRows = query.getPageRows();
        Integer offset = (page - 1) * pageRows;
        QueryWrapper<Car> wrapper = Wrappers.<Car>query()
                .eq(typeId != -1, "c.type_id", typeId)
                .eq(stateId != -1, "c.state_id", stateId)
                .like(StringUtils.isNotBlank(plate_code), "c.plate_code", plate_code);

        Integer rowsNum = baseMapper.queryCarNum(wrapper);
        List<Car> cars = baseMapper.queryCarList(wrapper, offset, pageRows);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("rowsNum", rowsNum);
        map.put("list", cars);
        return map;
    }

    /**
     * 删除车辆及其使用信息
     *
     * @param aid
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delCarByCarId(Integer aid) {
        carUserMapper.delByCarAid(aid);
        baseMapper.delByAid(aid);
        return true;
    }

    /**
     * 获取车辆详情
     *
     * @param id
     * @return
     */
    @Override
    public HashMap<Object, Object> getCarById(Integer id) {
        Car car = carService.getById(id);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("plateCode", car.getPlateCode());
        map.put("typeName", car.getTypeName());
        map.put("brand", car.getBrand());
        map.put("approvedNum", car.getApprovedNum());
        map.put("memo", car.getMemo());
        map.put("stateId", car.getStateId());
        map.put("stateName", car.getStateName());
        map.put("timeAdd", car.getTimeAdd());
        map.put("timeUpdateLast", car.getTimeUpdateLast());
        return map;
    }

    /**
     * 获取修改车辆信息
     *
     * @param aid 车辆aid
     * @return
     */
    @Override
    public HashMap<Object, Object> getUpdateCar(Integer aid) {
        List<CarUser> carUsers = carUserMapper.queryUserListByCarAid(aid);
        List<Integer> userList = new ArrayList<>();
        if (carUsers != null) {
            for (CarUser carUser : carUsers) {
                userList.add(carUser.getUserAid());
            }
        }
        Car car = carService.getById(aid);
        HashMap<Object, Object> map = new HashMap<>();
        map.put("plateCode", car.getPlateCode());
        map.put("typeId", car.getTypeId());
        map.put("brand", car.getBrand());
        map.put("approvedNum", car.getApprovedNum());
        map.put("memo", car.getMemo());
        map.put("stateId", car.getStateId());
        map.put("userList", userList);

        return map;
    }

    /**
     * 校验相同车牌号的其他车辆是否存在
     *
     * @param query
     * @return
     */
    @Override
    public HashMap<Object, Object> checkCarPlateCode(QueryCheckCarPlateCode query) {
        Integer aid = query.getAid();
        String plateCode = query.getPlateCode();
        QueryWrapper<Car> wrapper = Wrappers.<Car>query();
        if (aid == -1) {
            wrapper = Wrappers.<Car>query().eq("c.plate_code", plateCode);
        } else {
            wrapper = Wrappers.<Car>query().eq("c.plate_code", plateCode)
                    .ne("c.aid", aid);
        }
        Integer carNum = baseMapper.queryCarNum(wrapper);
        Boolean flag;
        if (carNum > 0) {
            flag = true;
        } else {
            flag = false;
        }
        HashMap<Object, Object> map = new HashMap<>();
        map.put("isExists", flag);
        return map;
    }

    /**
     * 新增 / 修改车辆
     *
     * @param car
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveCar(Car car) {

        String plateCode = car.getPlateCode();

        /*获取状态名称*/
        Integer typeId = car.getTypeId();
        String typeName = null;
        List<CarType> types = carTypeService.getCarTypeList();
        for (CarType type : types) {
            if (type.getId() == typeId) {
                typeName = type.getName();
            }
        }
        car.setTypeName(typeName);

        /*获取状态名称*/
        Integer stateId = car.getStateId();
        String stateName = null;
        List<CarState> states = carStateService.getCarStateList();
        for (CarState state : states) {
            if (state.getId() == stateId) {
                stateName = state.getName();
            }
        }
        car.setStateName(stateName);

        //判断新增/修改
        if (car.getAid() == -1) {
            carService.save(car);
        } else {
            carService.updateById(car);
        }

        /*更新车辆使用者*/
        carUserMapper.delByCarAid(car.getAid());    //先删除再增加
        List<Integer> userList = car.getUserList();
        if (!userList.isEmpty()) {
            for (Integer userId : userList) {
                CarUser carUser = new CarUser();
                carUser.setUserAid(userId);
                carUser.setCarAid(car.getAid());
                carUserService.save(carUser);
            }
        }
        return true;
    }

}
